package com.wodan.zhongjinjicang.common.orm.metadata;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.wodan.zhongjinjicang.common.orm.annotation.FieldType;
import com.wodan.zhongjinjicang.common.orm.utils.CaseInsensitiveString;
import org.springframework.util.Assert;


/**
 * 表字段的源数据
 * 
 * @ClassName: TableFieldMetaData
 * @author Administrator
 * @date 2015-11-5 上午9:27:01
 * @history
 * 
 */
public class TableFieldMetaData {
	private String fieldName;

	private CaseInsensitiveString columnName;

	private Method readMethod;

	private Method writeMethod;

	private FieldType fieldType;

	private Class<?> fieldObjetClass;
	
	public String getFieldName() {
		return fieldName;
	}

	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}

	public CaseInsensitiveString getColumnName() {
		return columnName;
	}

	public void setColumnName(CaseInsensitiveString columnName) {
		this.columnName = columnName;
	}

	public Method getReadMethod() {
		return readMethod;
	}

	public void setReadMethod(Method readMethod) {
		this.readMethod = readMethod;
	}

	public Method getWriteMethod() {
		return writeMethod;
	}

	public void setWriteMethod(Method writeMethod) {
		this.writeMethod = writeMethod;
	}

	public void setFieldType(FieldType fieldType) {
		this.fieldType = fieldType;
	}

	public FieldType getFieldType() {
		return fieldType;
	}

	public Object readFieldValue(Object entity) {
		Assert.notNull(entity);

		try {
			return readMethod.invoke(entity);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
			throw new RuntimeException(ex);
		}
	}

	public void writeFieldValue(Object entity, Object newValue) {
		Assert.notNull(entity);

		try {
			writeMethod.invoke(entity, newValue);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
			throw new RuntimeException("写方法执行抛出异常，方法名：[" + writeMethod.getName() + "]，参数类型：[" + newValue.getClass()
					+ "]，参数值：[" +  newValue + "]", ex);
		}
	}

	public boolean isIdField() {
		return FieldType.ID.equals(fieldType);
	}

	public void setFieldObjetClass(Class<?> fieldObjetClass) {
		this.fieldObjetClass = fieldObjetClass;
	}

	public Class<?> getFieldObjetClass() {
		return fieldObjetClass;
	}
}
